/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.web.editors;

import cn.easyplatform.entities.beans.table.TableField;
import org.zkoss.zk.ui.Page;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listitem;

import java.util.ArrayList;
import java.util.List;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
public class ListboxEditorCallback implements EditorCallback<TableInfo> {

	private Listbox listbox;

	private String title;

	private boolean checked;

	public ListboxEditorCallback(Listbox listbox, String title) {
		this(listbox, title, false);
	}

	public ListboxEditorCallback(Listbox listbox, String title, boolean checked) {
		this.listbox = listbox;
		this.title = title;
		this.checked = checked;
	}

	@Override
	public TableInfo getValue() {
		if (!checked || listbox.getItems().isEmpty())
			return null;
		List<TableField> data = new ArrayList<TableField>();
		for (Listitem row : listbox.getItems()) {
			TableField tf = row.getValue();
			data.add(tf);
		}
		return new TableInfo("", data);
	}

	@Override
	public void setValue(TableInfo table) {
		Events.postEvent(new Event(Events.ON_CHANGE, listbox, table));
	}

	@Override
	public String getTitle() {
		return title;
	}

	@Override
	public Page getPage() {
		return listbox.getPage();
	}

	@Override
	public Editor getEditor() {
		return null;
	}

}
